#include "bhxjglbasewidget.h"

BHXJGLBaseWidget::BHXJGLBaseWidget(QWidget *parent) : QOpenGLWidget(parent)
{
    setFocusPolicy(Qt::StrongFocus);
    timerID= startTimer(10);
}

void BHXJGLBaseWidget::mousePressEvent(QMouseEvent *e)
{
    if(e->button()==Qt::LeftButton)
    {
        setCursor(QCursor(Qt::BlankCursor));
        p=e->globalPos();
    }
}
void BHXJGLBaseWidget::mouseReleaseEvent(QMouseEvent *e)
{
    if(e->button()==Qt::LeftButton)
    {
        setCursor(QCursor(Qt::ArrowCursor));
    }
}
void BHXJGLBaseWidget::mouseMoveEvent(QMouseEvent *e)
{
    if(!move)
    {
        return;
    }
    move=false;
    {
        int pitch=p.y()-e->globalY();
        int yaw=e->globalX()-p.x();
        if(pitch==0&&yaw==0)
        {}
        else
        {
            QCursor::setPos(p);
            this->camera.SetPitch(camera.GetPitch()+pitch*0.15f);
            this->camera.SetYaw(camera.GetYaw()+yaw*0.15f);
            updated=true;
        }
    }
    move=true;
}


void BHXJGLBaseWidget::keyPressEvent(QKeyEvent *e)
{
    keys[e->key()] = true; QWidget::keyPressEvent(e);
}
void BHXJGLBaseWidget::keyReleaseEvent(QKeyEvent *e)
{
    keys[e->key()] = false; QWidget::keyReleaseEvent(e);
}

void BHXJGLBaseWidget::focusOutEvent(QFocusEvent *)
{
    keys.clear();
}

void BHXJGLBaseWidget::timerEvent(QTimerEvent *)
{
    if(keys[Qt::Key_W])
    {
        this->camera.ForWard_Move(0.06f);
        updated=true;
    }
    if(keys[Qt::Key_S])
    {
        this->camera.BackWard_Move(0.06f);
        updated=true;
    }
    if(keys[Qt::Key_A])
    {
        this->camera.LeftWard_Move(0.06f);
        updated=true;
    }
    if(keys[Qt::Key_D])
    {
        this->camera.RightWard_Move(0.06f);
        updated=true;
    }
    if(updated)
    {
        updated=false;
        //this->update();
        this->repaint();
    }
}

